package tech.dongling.boot.common.parser;

import cn.hutool.json.JSONUtil;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.multipart.*;
import tech.dongling.boot.common.base.HttpBizRequest;

import java.net.URI;
import java.nio.charset.StandardCharsets;

// HTTP请求解析器
public class HttpReqParser {
    public static HttpBizRequest parse(FullHttpRequest request) throws Exception {
        HttpBizRequest bizReq = new HttpBizRequest();
        URI uri = new URI(request.uri());
        bizReq.setPath(uri.getPath());

        // 解析GET参数
        QueryStringDecoder queryDecoder = new QueryStringDecoder(request.uri());
        queryDecoder.parameters().forEach((k, v) -> bizReq.getParams().put(k, v.get(0)));

        // 解析POST数据
        if (HttpMethod.POST.equals(request.method())) {
            String contentType = request.headers().get(HttpHeaderNames.CONTENT_TYPE);
            if (contentType != null) {
                if (contentType.startsWith(HttpHeaderValues.APPLICATION_JSON.toString())) {
                    String json = request.content().toString(StandardCharsets.UTF_8);
                    bizReq.setBody(JSONUtil.parseObj(json));
                } else if (contentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString())) {
                    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(), request);
                    for (InterfaceHttpData data : decoder.getBodyHttpDatas()) {
                        if (data instanceof Attribute attr) {
                            bizReq.getParams().put(attr.getName(), attr.getValue());
                        } else if (data instanceof FileUpload file) {
                            bizReq.getFiles().put(file.getFilename(), file.get());
                        }
                    }
                }
            }
        }
        return bizReq;
    }
}